package com.laxcen.basiclib.base;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;

import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;

import com.laxcen.basiclib.BaseConst;
import com.laxcen.basiclib.core.broadcast.BroadcastManager;
import com.laxcen.basiclib.engine.ApiEngine;
import com.laxcen.basiclib.ui.activity.WeexActivity;
import com.laxcen.basiclib.ui.dialog.CrashDialog;
import com.laxcen.basiclib.utils.ActivityCollectorUtil;


/**
 * BaseActivity
 */
public abstract class BaseActivity extends FragmentActivity{

    protected Context mContext;
    protected ApiEngine api;
    protected BroadcastManager broadcastManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this ;
        api = ApiEngine.bind(this);
        ActivityCollectorUtil.addActivity(this);
        initBroadcast();
    }


    protected void onPause() {
        super.onPause();
        if(isFinishing()){
            ActivityCollectorUtil.removeActivity(this);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        api.onActivityResult(requestCode,resultCode,data);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        api.unBind();
        destroyBroadcast();
    }


    //////////////////////////////////////下面是基础平台的一些系统功能/////////////////////////////////


    /**
     * 初始化系统默认的广播
     */
    private void initBroadcast(){
        broadcastManager = BroadcastManager.getInstance(this);
        broadcastManager.register(BaseConst.CAUGHT_EXCEPTION, new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String title = intent.getStringExtra("title");
                String text = intent.getStringExtra("context");
                CrashDialog crashDialog = new CrashDialog(BaseActivity.this);
                crashDialog.setData(title,text);
                crashDialog.setOnResult(new CrashDialog.OnResult() {
                    @Override
                    public void onReboot() {
                        api.reloadApp();
                    }

                    @Override
                    public void onClose() {
                        api.finishApp();
                    }

                    @Override
                    public void onCancel() {
                        crashDialog.dismiss();
                    }
                });
                crashDialog.show(0, Gravity.CENTER);
            }
        });
    }

    /**
     * 销毁系统默认的广播
     */
    private void destroyBroadcast(){
        broadcastManager.unregister(BaseConst.CAUGHT_EXCEPTION);
    }
}